package com.haier.cloudremote.protocal;

import java.io.IOException;
import java.net.Socket;
import java.nio.ByteBuffer;

import com.haier.cloudremote.common.SLog;
import com.haier.cloudremote.model.StateInfo;
import com.haier.cloudremote.model.StbInfo;
import com.haier.cloudremote.model.StbList;

public class CAEProtocal {

	public static SocketPackte socketPackte = new SocketPackte();

	/**
	 * 开始学习
	 * 
	 * @param socketPackte
	 * @return 返回码 1002 准备好开始学习 -1100 CRB 设备未找到 -1000 其他错误 -2000 socket no
	 *         create
	 */
	public static int startStudy() {
		int returnCode;
		try {
			Socket socket = socketPackte.createLongSocket();
		} catch (IOException e) {// 连接被拒绝，可能原因：CAE未启动
			// TODO Auto-generated catch block
			return -2000;
		}

		byte type = 0x00;
		byte[] bytekeyV = new byte[1];
		bytekeyV[0] = 0x00;
		ByteBuffer data = PackageOperation.setPackgeDataformSSCStudy(type,
				bytekeyV);
		try {
			socketPackte.sendPacket(ConnectManager.CMD_SSC_LEARN, 0, data);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			socketPackte.closeSocket();
		}
		returnCode = (Integer) socketPackte.reciveStudyPacket();

		return returnCode;
	}

	/**
	 * 学习按键
	 * 
	 * @param socketPackte2
	 * @param keyNum
	 *            提示用户按键，键值
	 * @param isSendKey
	 * @return 返回码，键值 1004 收到的是TV按键，需要UI提示 用户操作STB按键 -1100 CRB 设备未找到 -1000 其他错误
	 *         -2000 socket no create -2001 与CAE的连接断开 1005
	 *         超过3秒未收到CRB回应（CRB出错，或者用户未按键，提示用户按键）
	 */
	public static int studyOfKey(int keyNum, Boolean isSendKey) {
		SLog.d("ssc", "CAEProtocal----------studyOfKey()---keyNum==" + keyNum);
		int keyCode;

		byte type = (byte) 0x01;
		ByteBuffer data = PackageOperation.setPackgeDataformSSCStudy(type,
				ConnectManager.intToByte(keyNum));
		try {
			socketPackte.sendPacket(ConnectManager.CMD_SSC_LEARN, 0, data);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			socketPackte.closeSocket();
		}
		keyCode = socketPackte.reciveStudyPacket();

		return keyCode;
	}

	/**
	 * 结束学习
	 * 
	 * @param socketPackte
	 * @return 返回码 1001（用户有按键） 当UI收到这个消息时，提示用户按下一个匹配键 1002 准备好开始学习 1003 学习结束
	 *         -1000 其他错误 -2000 socket no create
	 */
	public static int finishStudy() {
		int returnCode;
		byte type = (byte) 0xFF;
		byte[] bytekeyV = new byte[1];
		bytekeyV[0] = (byte) 0xFF;
		ByteBuffer data = PackageOperation.setPackgeDataformSSCStudy(type,
				bytekeyV);
		try {
			socketPackte.sendPacket(ConnectManager.CMD_SSC_LEARN, 0, data);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			return -2000;
		} finally {
			socketPackte.closeSocket();
		}
		returnCode = (Integer) socketPackte.reciveStudyPacket();

		return returnCode;
	}

	/**
	 * 获取机顶盒列表
	 * 
	 * @param province
	 *            所在省
	 * @param city
	 *            所在市
	 * @param region
	 *            所在区
	 * @param tvType
	 *            电视型号
	 * @return 机顶盒列表
	 */
	public static StbList getStbListFromCAE(int provinceId, int cityId,
			int townId, String tvType) {
		StbList stbList = null;

		try {
			socketPackte.getShortSocket();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			return null;
		}

		PackageOperation packageOperation = new PackageOperation();
		ByteBuffer data = packageOperation.setPackgeDataformRequestSTlist(0,
				provinceId, cityId, townId, tvType);
		try {
			socketPackte.sendPacket(ConnectManager.CMD_SSC_GETSTBLIST, 0, data);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			return null;
		}
		stbList = socketPackte.receiveGetStbRe();

		return stbList;
	}

	/**
	 * 用户选择的所用的机顶盒
	 * 
	 * @param stbInfo
	 *            机顶盒
	 * @return 返回码 1001 成功 -1003 其他错误 -2000 socket no create
	 */
	public static int setStb(StbInfo stbInfo) {
		int returnCode = -1003;

		try {
			socketPackte.getShortSocket();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			return -2000;
		}

		PackageOperation packageOperation = new PackageOperation();
		ByteBuffer data = packageOperation.setPackgeDataformSelectSTB(stbInfo
				.getStbId());
		try {
			socketPackte.sendPacket(ConnectManager.CMD_SSC_ON_USER_SELECTED, 0,
					data);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			return -2000;
		}
		returnCode = socketPackte.receiveSetStbRe();
		return returnCode;
	}

	/**
	 * 获取SSC状态:1. 返回学习进度 2. 返回所选通道 3. 返回是否开机启动
	 * 
	 * @return 为0是代表获取数据失败或获取的数据不可用 -2000 socket no create
	 */
	public static int getSSCState(int type) {
		// TODO Auto-generated method stub
		try {
			socketPackte.getShortSocket();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			return -2000;
		}
		ByteBuffer data = PackageOperation.setPackgeDataformGetState(type);
		try {
			socketPackte.sendPacket(ConnectManager.CMD_SSC_RETURN_STATUS, 0,
					data);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			return -2000;
		}
		StateInfo stateInfo = socketPackte.receiveGetSSCStateRe();

		if (stateInfo != null) {
			SLog.d("ssc", "stateInfo(type,value)===" + stateInfo.getType()
					+ "," + stateInfo.getValue());
			if (stateInfo.getType() == type) {
				return stateInfo.getValue();
			} else {
				return 0;
			}
		} else {
			return 0;
		}

	}

	/**
	 * 设置用户选择的STB通道
	 * 
	 * @param stbNum
	 *            通道序号
	 * @return 返回码 1001 成功 -1003 其他错误
	 */
	public static int setHDMI(int hdmiNum) {
		Integer returnCode = -1003;

		try {
			socketPackte.getShortSocket();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			return -2000;
		}

		ByteBuffer data = PackageOperation
				.setPackgeDataformSetSTBChannel(hdmiNum);
		try {
			socketPackte.sendPacket(ConnectManager.CMD_SSC_ON_STB_CHANNEL, 0,
					data);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			return -2000;
		}
		returnCode = socketPackte.receiveSetChannelRe();

		return returnCode;
	}

	/**
	 * 用户选择是否开机启动
	 * 
	 * @param switchCode
	 *            是否开机启动，（1Or 0）
	 * @return 1001 成功 -1003 其他错误 -2000 socket no create
	 */
	public static int setBootupSwitch(int switchCode) {
		Integer returnCode = -1003;

		try {
			socketPackte.getShortSocket();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			return -2000;
		}

		ByteBuffer data = PackageOperation
				.setPackgeDataformSetBootupSwitch(switchCode);
		try {
			socketPackte.sendPacket(ConnectManager.CMD_SSC_ON_STB_AUTO_ON, 0,
					data);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			return -2000;
		}
		returnCode = socketPackte.receiveSetBootSwitchRe();

		return returnCode;

	}

	/**
	 * 上传该地区机顶盒列表
	 * 
	 * @param province
	 * @param city
	 * @param town
	 * @param isShare
	 *            是否分享
	 * @param stbName
	 *            机顶盒型号
	 * @return 返回码 1001 ：成功分享 -1001 无法链接服务器 -1002 连接服务器超时 -1000 其他错误 -2000
	 *         socket no create
	 */
	public static int uploadStudiedSTB(int provinceId, int cityId, int townId,
			byte isShare, String stbName) {
		// TODO Auto-generated method stub
		Integer returnCode = -1000;

		try {
			socketPackte.getShortSocket();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			return -2000;
		}

		ByteBuffer data = PackageOperation.setPackgeDataformSTBlistToCould(0,
				provinceId, cityId, townId, isShare, stbName);
		try {
			socketPackte.sendPacket(ConnectManager.CMD_SSC_SHARE_KEYMAP, 0,
					data);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			return -2000;
		}
		returnCode = socketPackte.receiveUploadStbRe();

		return returnCode;

	}

	/**
	 * Debug 开关
	 * 
	 * @param debug
	 *            0 关闭，1打开
	 * @return 1001 成功 -1000 其他错误 -2000 socket no create
	 */
	public static int switchOfDebug(int debug) {
		// SLog.d("ssc", "switchOfDebug-----------");
		Integer returnCode = -1000;
		try {
			socketPackte.getShortSocket();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			return -2000;
		}
//		new Thread() {
//
//			public void run() {
//			};
//		}.start();

		ByteBuffer data = PackageOperation
				.setPackgeDataformswitchOfDebug(debug);
		try {
			socketPackte.sendPacket(ConnectManager.CMD_SSC_ON_DEBUG, 0, data);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			return -2000;
		}
		returnCode = socketPackte.receiveDebugSwitchRe();

		return returnCode;
	}

	/**
	 * 获取SSC 文件 存放路径
	 * 
	 * @param fileType
	 *            0 ：获取 Log路径 1 ：获取键值表存放路径
	 * @return 根据type返回对应的文件 完整存放路径 如果未获取到返回null
	 */
	public static String getFilePath(int fileType) {
		// SLog.d("ssc", "getFilePath-----------");
		String filePath = null;

		try {
			socketPackte.getShortSocket();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			return null;
		}

		ByteBuffer data = PackageOperation
				.setPackgeDataformGetFilePath(fileType);
		try {
			socketPackte
					.sendPacket(ConnectManager.CMD_SSC_GET_SSCFILE, 0, data);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			return null;
		}
		filePath = socketPackte.receiveFilepathRe();

		return filePath;
	}

	/**
	 * 测试STB
	 * 
	 * @param keyNum
	 *            电视遥控器键值 对应的SSC 键值
	 * @return 返回码 1001 成功 -1002 没有找到 对应的键值编码 -1003 其他错误 -2000 socket no create
	 */
	public static int testSTB(int keyNum) {
		int returnCode = -1003;

		try {
			socketPackte.getShortSocket();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			return -2000;
		}

		ByteBuffer data = PackageOperation.setPackgeDataformTestSTB(keyNum);
		try {
			socketPackte.sendPacket(ConnectManager.CMD_SSC_ON_TV_REMOTE, 0,
					data);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			return -2000;
		}

		returnCode = socketPackte.receiveTestSTBRe();

		return returnCode;
	}

}
